<?php

namespace app\api\controller;

use addons\signin\library\Service;
use addons\vip\library\Order;
use addons\vip\model\Record;
use addons\vip\model\Vip as VipModel;
use app\admin\model\banner\Banner;
use app\admin\model\Bookclass;
use app\admin\model\bookjieorder\Bookjieorder;
use app\admin\model\Books;
use app\admin\model\books\Booksjie;
use app\admin\model\card\Cardlog;
use app\admin\model\card\Carduser;
use app\admin\model\content\Content;
use app\admin\model\gift\Gift;
use app\admin\model\teacher\Share;
use app\admin\model\teacher\Teacher;
use app\admin\model\view\Card;
use app\admin\model\vip\Viprecore;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\User;
use fast\Date;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * @param string like 1男2女
     * @param string type 1小说2漫画
     * @param string token token
     */
    public function index()
    {

        $token = $this->auth->getToken();
        $like = $this->request->get('like');
        $type = $this->request->get('type');

        if ($token != '' && $like == 0) {
            $uid = $this->getToken($token);
            $userInfo = (new \app\admin\model\User())->find($uid);
            $like = $userInfo['like'];
        }
        if ($like == 2) {
            $catid = 4;
        } else {
            $catid = 1;
        }

        if ($type == 1) {
            $classModel = 'fa_bookclass';
            $class_id_name = "bookclass_id";
            $class_id_name2 = "bookclass_id";
            $BookModel = 'fa_books';
        }
        if ($type == 2) {
            $classModel = 'fa_cartoonclass';
            $class_id_name = "cartoonclass_id";
            $class_id_name2 = "class_id";
            $BookModel = 'fa_cartoon';
        }

        $erList = Db::table($classModel)->where([$class_id_name => $catid, 'status' => 1])->order('weigh desc')->select();

        $erChar = '';
        foreach ($erList as $key => $value) {
            if ($key == 0) {
                $erChar .= $value['id'];
            } else {
                $erChar .= ',' . $value['id'];
            }
        }
        //二级分类列表
        $catewhere = "status = 1";
        $catewhere .= " && $class_id_name In (" . $erChar . ")";
        $cateList = Db::table($classModel)->where($catewhere)->limit(3)->order('weigh desc')->select();
        foreach ($cateList as $key => $value) {
            $cateList[$key]['books'] = Db::table($BookModel)->where([$class_id_name2 => $value['id'], 'status' => 1])->limit(6)->order('weigh desc')->select();
        }

        //轮播图列表
        $bannerList = (new Banner())->where('status', 1)->order('weigh desc')->select();

        $data = [];
        $data['cateList'] = $cateList;
        $data['bannerList'] = $bannerList;
        $data['like'] = $like;
        $this->success('请求成功', $data);
    }

    /**
     * 选择分类
     * @ApiMethod (GET)
     * @param int like 类型  1男2女
     * */
    public function cateList()
    {
        $like = $this->request->get('like');
        if ($like == 2) {
            $catid = 4;
        } else {
            $catid = 1;
        }
        $typeList = (new Bookclass())->getAllList2($catid);
        $this->success('请求成功', $typeList);
    }

    /**
     * 获取用户协议和隐私政策
     * @ApiMethod (GET)
     * @param int type 类型  1隐私政策2用户协议3会员协议
     **/
    public function getContent()
    {
        $contentList = (new Content())->where('id', $this->request->get('type'))->select();
        $this->success('请求成功', $contentList);
    }

    /**
     * @ApiTitle    (获取观阅任务列表)
     * @ApiMethod   (GET)
     * @ApiReturnParams   (name="name", type="string", required=true,, description="优惠券名称", sample="")
     **/
    public function get_view_card()
    {
//        $aa  =  new Carduser();
//        $aa->id = 1;
//        $bb = $aa->add();
//        $this->success('请求成功',$bb);

        $cardList = Db::table('fa_view_card')->whereNull('deletetime')->order('weigh')->select();
        $this->success('请求成功', $cardList);
    }

    /**
     * 观阅币兑换观阅包
     * @ApiMethod (GET)
     * @param string card_id 观阅包id
     **/
    public function moneyViewCard()
    {
        $token = $this->auth->getToken();
        $card_id = $this->request->get('card_id');
        $uid = $this->getToken($token);
        $user_info = (new \app\admin\model\User())->find($uid);
        $share_info = (new Share())->where(['user_id' => $uid])->find();
        $card_info = (new Card())->where('id', $card_id)->find();

        if (empty($card_info)) {
            $this->error('观阅包不存在');
        }

        if ($card_info['type'] != 1) {
            $this->error('此观阅包领取类型为' . $card_info['type'] . '现金购买');

        }

        if ($user_info['money'] < $card_info['need']) {
            $this->error('余额不足');
        }

        Db::startTrans();
        try {
            $Carduser = new Carduser();
            $Carduser->user_id = $uid;
            $Carduser->card_id = $card_id;
            $Carduser->card_type = 1;
            $result = $Carduser->add();

            User::money(-$card_info['need'], $uid, '购买观阅包');

            $share = new Share();
            $share->where(['user_id' => $uid])->setDec('money', $card_info['need']);

            if ($user_info['pid'] > 0) {
                $this->shangjia($uid, $user_info['pid'], 1, $card_info['active']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if ($result == 1) {
            $this->success('成功', $result);
        } else {
            $this->error($result);
        }
    }


    /*
     * 为上级增加活跃值
     */
    public function shangjia($uid, $pid, $type, $active)
    {
        $user = (new \app\admin\model\User())->find($pid);
        if ($user['pid'] > 0) {
            $data = [
                'user_id' => $uid,
                'pid' => $pid,
                'addtime' => time(),
                'active' => $active,
                'memo' => '下级购买观阅包产出',
                'type' => $type,
            ];
            if ($type == 1) {
                Db::table('fa_share')->where(['user_id' => $user['pid']])->setInc('active_qu', $active);
            } else {
                Db::table('fa_share')->where(['user_id' => $user['pid']])->setInc('active_zong', $active);
            }

            $this->shangjia($uid, $pid, 2);
        }
    }


    /**
     * 现金兑换观阅包下单
     * @ApiMethod (GET)
     * @param string card_id 观阅包id
     * @param int appid appid
     * @param int paytype 支付方式 alipay,wechat
     **/
    public function buyViewCard()
    {
        $token = $this->auth->getToken();
        $card_id = $this->request->get('card_id');
        $appid = $this->request->get('appid');
        $paytype = $this->request->get('paytype');
        $uid = $this->getToken($token);
        $user_info = (new \app\admin\model\User())->find($uid);
        $share_info = (new Share())->where(['user_id' => $uid])->find();
        $card_info = (new Card())->where('id', $card_id)->find();

        if (empty($card_info)) {
            $this->error('观阅包不存在');
        }


        Db::startTrans();
        try {
            $order_data = [
                'user_id' => $uid,
                'card_id' => $card_id,
                'orderid' => time() . $uid,
                'method' => $paytype,
                'addtime' => time(),
            ];

            $order_info = Db::table('fa_view_card_order')->insertGetId($order_data);
            $notifyurl = $this->request->root(true) . '/addons/epay/api/cardnotifyx/type/' . $paytype;
            $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype;
            $response = Order::cardsubmit($card_id, $order_info, $card_info['need'], $paytype, 'app', '', $notifyurl, $returnurl);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功', $response);
    }

    /**
     * 查询是否有任务
     * @ApiMethod (GET)
     **/
    public function getViewCardLog()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);


        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b', 'a.card_id = b.id', 'left')
            ->where('a.status', '=', 1)
            ->where('a.user_id', '=', $uid)
            ->where('a.endtime', '>', time())
            ->field('a.id,a.card_id,a.user_id,b.day_nums,b.name')
            ->select();

        if (empty($list)) {
            $this->success('暂无进行中任务', 0);
        }

        // 获取当前日期的 0 点时间戳
        $todayStartTimestamp = strtotime(date('Y-m-d 00:00:00'));
        // 获取当前日期的 24 点时间戳（即第二天的 0 点）
        $todayEndTimestamp = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
        $num = 0;
        foreach ($list as $key => $value) {
            $info = Db::table('fa_view_card_log')
                ->where('card_id', $value['card_id'])
                ->where('user_id', $value['user_id'])
                ->where('log_id', $value['id'])
                ->where('addtime', '>=', $todayStartTimestamp) // 时间大于等于开始时间戳
                ->where('addtime', '<=', $todayEndTimestamp) // 时间小于等于结束时间戳
                ->find();

            if (empty($info)) {
                $num++;
            }
        }

        $this->success('获取成功', $num);

    }


    /**
     * 查询我的任务列表
     * @ApiMethod (GET)
     **/
    public function getViewCardList()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b', 'a.card_id = b.id', 'left')
            ->where('a.status', '=', 1)
            ->where('a.user_id', '=', $uid)
            ->where('a.endtime', '>', time())
            ->field('a.*,b.day_nums,b.name')
            ->select();

        $this->success('获取成功', $list);

    }


    /**
     * 观看小说获得观阅收益
     * @ApiMethod (GET)
     **/
    public function getViewCardMoney()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b', 'a.card_id = b.id', 'left')
            ->where('a.status', '=', 1)
            ->where('a.user_id', '=', $uid)
            ->where('a.endtime', '>', time())
            ->field('a.id,a.card_id,a.user_id,b.day_nums,b.name')
            ->select();

        if (empty($list)) {
            $this->success('暂无进行中任务');
        }

        // 获取当前日期的 0 点时间戳
        $todayStartTimestamp = strtotime(date('Y-m-d 00:00:00'));
        // 获取当前日期的 24 点时间戳（即第二天的 0 点）
        $todayEndTimestamp = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
        foreach ($list as $key => $value) {
            $info = Db::table('fa_view_card_log')
                ->where('card_id', $value['card_id'])
                ->where('user_id', $value['user_id'])
                ->where('log_id', $value['id'])
                ->where('addtime', '>=', $todayStartTimestamp) // 时间大于等于开始时间戳
                ->where('addtime', '<=', $todayEndTimestamp) // 时间小于等于结束时间戳
                ->find();
            if (empty($info)) {
                $data = [
                    'user_id' => $value['user_id'],
                    'card_id' => $value['card_id'],
                    'log_id' => $value['id'],
                    'day_nums' => $value['day_nums'],
                    'addtime' => time(),
                ];
                Db::startTrans();
                try {
                    Db::table('fa_view_card_log')->insert($data);
                    Db::table('fa_view_card_user')->where('id', $value['id'])->update(['updatedtime' => time()]);
                    Db::table('fa_view_card_user')->where('id', $value['id'])->setInc('day_now');
                    Db::table('fa_view_card_user')->where('id', $value['id'])->setDec('day_no');

                    $result = User::money(+$value['day_nums'], $value['user_id'], $value['name'] . '观阅任务获得收益');

                    $share = new Share();
                    $share->where(['user_id' => $uid])->setInc('money', $value['day_nums']);
                    $share->where(['user_id' => $uid])->setInc('total_money', $value['day_nums']);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }
        $this->success('成功', $result);
    }


    /**
     * 更新数据
     * @ApiMethod (GET)
     **/
    public function gengxin()
    {
        $userList = Db::table('fa_user')->select();

        foreach ($userList as $key => $value) {
            $info = Db::table('fa_share')->where(['user_id' => $value['id']])->find();

            if ($info) {
                $pushall = $info['first_children'] + 1;

                $teacher = new Teacher();
                if ($info['teacher_id'] > 0) {
                    $teacher->id = $info['teacher_id'];
                }
                $teacher->push = $pushall;
                $teacherInfo = $teacher->shengji();

                if ($teacherInfo && $teacherInfo['id'] != $info['teacher_id']) {

                    $share = new Share();
                    $new_data['teacher_id'] = $teacherInfo['id'];
                    $new_data['updatedtime'] = time();

                    $share->where(['id' => $info['id']])->update($new_data);

                    $Carduser = new Carduser();
                    $card_id = $teacherInfo['card_id'];

                    $Carduser->user_id = $pid;
                    $Carduser->card_id = $card_id;
                    $Carduser->card_type = 2;
                    $cardUserreslt = $Carduser->add();
                }

                Db::table('fa_share')->where(['id' => $info['id']])->setInc('all_children');
                Db::table('fa_share')->where(['id' => $info['id']])->setInc('first_children');

                $this->shangjia($pid);

            } else {
                Db::table('fa_share')->insertGetId(['user_id' => $pid, 'addtime' => time(), 'all_children' => 1, 'first_children' => 1]);
            }
        }
    }


    /**
     * 我的粉丝
     * @ApiMethod (GET)
     **/
    public function myfans()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,pid,nickname,avatar')->find($uid);
        $userInfo['p_info'] = [];
        $userInfo['fans_list'] = [];

        if ($userInfo['pid'] > 0) {
            $userInfo['p_info'] = $User->field('id,pid,nickname,avatar,userId')->find($userInfo['pid']);
            $addtime = Db::table('fa_share_log')->where(['user_id' => $uid, 'pid' => $userInfo['pid']])->find();
            $userInfo['p_info']['addtime'] = date('Y-m-d H:i:s', $addtime['addtime']);
        }

        $userInfo['fans_list'] = Db::table('fa_share_log')
            ->alias('a')
            ->join('fa_user b', 'a.user_id = b.id', 'left')
            ->where('a.pid', '=', $uid)
            ->field('a.id,b.avatar,b.nickname,FROM_UNIXTIME(addtime, "%Y/%m/%d %H:%i:%s") as addtime')
            ->order('a.addtime desc')
            ->select();

        $userInfo['fans_count'] = Db::table('fa_share_log')
            ->alias('a')
            ->join('fa_user b', 'a.user_id = b.id', 'left')
            ->where('a.pid', '=', $uid)
            ->count();

        $fa_share = (new Share())->where(['user_id' => $uid])->find();
        $userInfo['active'] = $fa_share['active_zong'] - $fa_share['active_qu'];

        $this->success('成功', $userInfo);

    }


    /**
     * 我的书券
     * @ApiMethod (GET)
     **/
    public function mymoney()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,money')->find($uid);
        $userInfo['money_log'] = (new MoneyLog())->where('user_id', $uid)->field('*,FROM_UNIXTIME(createtime, "%Y/%m/%d %H:%i:%s") as createtime')->select();

        $this->success('成功', $userInfo);
    }


    /**
     * 我的金币
     * @ApiMethod (GET)
     **/
    public function myscore()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,score')->find($uid);
        $userInfo['money_log'] = (new ScoreLog())->where('user_id', $uid)->field('*,FROM_UNIXTIME(createtime, "%Y/%m/%d %H:%i:%s") as createtime')->select();

        $this->success('成功', $userInfo);
    }


    /**
     * 充值中心页面
     * @ApiMethod (GET)
     **/
    public function moneyConfig()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money')->find($uid);
        $userInfo['money_config'] = (new \app\admin\model\money\Money())->where('status', 1)->order('weigh desc')->select();
        $site = config('site');
        $score_config['convert'] = $site['convert'];
        $score_config['money'] = $userInfo['money'];
        $score_config['score_get'] = $userInfo['money'] * $site['convert'];
        $userInfo['score_config'] = $score_config;

        $this->success('请求成功', $userInfo);
    }


    /**
     * 书券兑换
     * @ApiMethod (GET)
     * @param string money 书券数量
     **/
    public function convert_money()
    {
        $token = $this->auth->getToken();
        $money = $this->request->get('money');
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money')->find($uid);
        $site = config('site');
        $convert = $site['convert'];

        if ($userInfo['money'] < $money) {
            $this->error('书券余额不足');
        }

        $socore = $money * $convert;
        Db::startTrans();
        try {
            User::money(-$money, $uid, '兑换金币扣除');
            User::score(+$socore, $uid, '使用书券兑换获得');

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功');
    }

    /**
     * 兑换比例接口
     * @ApiMethod (GET)
     **/
    public function convert()
    {
        $site = config('site');
        $convert = $site['convert'];
        $this->success('成功', $convert);
    }


    /**
     * 转增书券
     * @ApiMethod (GET)
     * @param string money 书券数量
     * @param string mobile 转赠用户手机号
     * @author 杜洋
     **/
    public function givemoney()
    {
        $token = $this->auth->getToken();
        $money = $this->request->get('money');
        $mobile = $this->request->get('mobile');
        $password = $this->request->get('password');
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money,nickname,pay_pass,pid')->find($uid);
//        halt($userInfo['money']);
        $userInfo2 = $User->field('id,score,money,nickname')->where('mobile', $mobile)->find();
        if ($userInfo['money'] < $money) {
            $this->error('书券余额不足');
        }
        if ($userInfo2['id'] == $uid) {
            $this->error('不能转赠自己');
        }
        //验证交易密码
//            halt($userInfo['pay_pass']);
        if ($userInfo['pay_pass'] != $password) {
            $this->error('交易密码错误');
        }
        try {
            //查询有多少直推下级
            $count = $User->where(['pid' => $uid, 'status' => 'normal'])->count();
            //转赠规则
            $data = (new Gift())->field('id,criteria,value,desc')->select();
            $datacriteria = array_column($data, 'criteria');
            $datavalue = array_column($data, 'value');
            foreach ($datacriteria as $index => $criteria) {
                if ($count < $criteria) {
                    //扣除的书券
                    $deductMoney = $money / (1 - $datavalue[$index - 1]);
                    break;
                }
            }
            if (end($datacriteria) <= $count) {
                //扣除的书券
                $deductMoney = $money / end($datavalue);
            }

            $bonus = (new Teacher())->field('bonus')->select();
            //取所有的bonus
            $totalBonus = 0;
            $one = []; // 初始化一个空数组来存储每个计算结果
            foreach ($bonus as $k => $item) {
                $totalBonus += $item['bonus'];
                $one[] = $item['bonus'] * ($deductMoney - $money); // 将计算结果添加到数组中
            }
            $currentMoney = DB::table('fa_book_bonus')
                ->field('money_one,money_two,money_three,money_four,money_five')
                ->find();
            DB::table('fa_book_bonus')
                ->where('id', 1)
                ->update(['money_one' => $currentMoney['money_one'] + $one[0], 'money_two' => $currentMoney['money_two'] + $one[1], 'money_three' => $currentMoney['money_three'] + $one[2], 'money_four' => $currentMoney['money_four'] + $one[3], 'money_five' => $currentMoney['money_five'] + $one[4]]);
            Db::startTrans();
            User::money(-$deductMoney, $uid, '转增用户' . $userInfo2['nickname'] . '扣除');
            User::money(+$money, $userInfo2['id'], '用户' . $userInfo['nickname'] . '转增获得');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('转赠成功', '转赠金额:' . $money . ' 扣除金额:' . $deductMoney . ' 实际转增金额:' . $money);
    }

    /**
     * @ApiMethod (GET)
     * 定时分红
     */
    public function bonus()
    {
        //查询等级用户和数量
        $shareData = (new Share())->where('teacher_id', '>', 0)->field('id,user_id,teacher_id')->select();
        $teacherData = (new Teacher())->field('id,name')->order('weigh', 'asc')->select();
        $currentMoney = DB::table('fa_book_bonus')
            ->field('money_one,money_two,money_three,money_four,money_five')
            ->find();
        try {
            $users = [];
            foreach ($shareData as $item) {
                foreach ($teacherData as $teacher) {
                    if ($teacher['id'] == $item['teacher_id']) {
                        $users[$teacher['name']][] = $item['user_id'];
                        break;
                    }
                }
            }
            // 调整键的顺序
            $keys = array_keys($users);
            $sortedKeys = ["青铜观阅师", "白银观阅师", "黄金观阅师", "钻石观阅师", "王者观阅师"];
            $sortedData = [];
            // 根据调整后的顺序重新索引数组元素
            foreach ($sortedKeys as $key) {
                if (in_array($key, $keys)) {
                    $sortedData[$key] = $users[$key];
                    unset($keys[array_search($key, $keys)]); // 从原始键数组中移除已使用的键
                }
            }
            //每个等级的用户数量
            $countValue = [];
            //每个等级的用户id
            //每个等级的奖池金额
            $countMoney = [];
            foreach ($sortedData as $key => $value) { //3
                $countValue[] = count($value);
            }
//            halt($countValue);
            foreach ($currentMoney as $k => $v) {
                $countMoney[] = $v;
            }
            //每个等级里的用户分得的金额
            $results = [];
            foreach ($countValue as $index => $value) {
                $money = (float)str_replace(",", ".", $countMoney[$index]);
                $result = $money / $value;
                $results[] = $result;
            }
//            halt($results);
            //开始分配金额
            $usersId = 0;
            $moneyId = 0;
            foreach ($sortedData as $key => $value) {
                foreach ($value as $item) {
                    User::money(+floatval($results[$moneyId]), $item, '书券分红');
                    //扣除奖池
                    $usersId++;
                }
                $moneyId++;
            }
            //判断金额是否大于0
            DB::table('fa_book_bonus')
                ->where('id', 1)
                ->update([
                    'money_one' => DB::raw('money_one - ' . $results[0] * $countValue[0]),
                    'money_two' => DB::raw('money_two - ' . $results[1] * $countValue[1]),
                    'money_three' => DB::raw('money_three - ' . $results[2] * $countValue[2]),
                    'money_four' => DB::raw('money_four - ' . $results[3] * $countValue[3]),
                    'money_five' => DB::raw('money_five - ' . $results[4] * $countValue[4])
                ]);
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功', $results);
    }

    /**
     * 赠送体验包
     */
    public function getViewCard()
    {
        //接收手机号
        $mobile = $this->request->get('mobile/d');
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $exper_number = User::where('id', $uid)->value('exper_number');
        if ($exper_number <= 0) {
            $this->error('体验包数量不足！');
        }
        //验证手机号是否存在
        $userInfo = User::where('mobile', $mobile)->find();
        if (!$userInfo) {
            $this->error('用户不存在!');
        }
        //验证受赠人是否有观阅包
        $isCard = Db::table('fa_view_card_user')->where('user_id', $userInfo['id'])->find();
        if ($isCard) {
            $this->error('该用户不符合赠送规则');
        }
        $order_data = [
            'user_id' => $userInfo['id'],
            'card_id' => 1,
            'card_type' => 3,
            'day_count' => 30,
            'day_now' => 1,
            'day_no' => 29,
            'starttime' => time(),
            'endtime' => time() + 2592000,
            'addtime' => time()
        ];
        try {
            Db::table('fa_user')->where('id', $uid)->update(['exper_number' => $exper_number - 1]);
            Db::startTrans();
            Db::table('fa_view_card_user')->insertGetId($order_data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('赠送失败');
        }
        $this->success('赠送成功');
    }

    /**
     *活跃值查询 首页
     * @ApiMethod (GET)
     */
    public function getActive()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $share = new Share();
        $shareActive = $share->where('user_id', $uid)->field('active_zong')->select()->toArray();
        $this->success('成功', $shareActive);
    }

    /**
     * 活跃值查询大区
     * @ApiMethod (GET)
     */
    public function getActiveItem()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
//        //查询有多少直推下级
        $User = new User();
        $userInfo = $User->field('id')->where(['pid' => $uid])->select()->toArray();
        $ids_to_check = array_column($userInfo, 'id');//直推用户的user_id
        $share = new Share();
        foreach ($ids_to_check as $k => $item) { //直推用户的数据
            $shareData[] = $share->field('id,user_id,active_zong,active_qu,all_children')->where('user_id', $item)->select()->toArray();//下级用户
        }
        $maxChildren = 0;
        foreach ($shareData as $item) {
            $counts[] = count($item);
            //求大区
            if (count($item) > 0 && isset($item[0]['all_children']) && $item[0]['all_children'] > $maxChildren) {
                $maxArray = $item;
                $maxChildren = $item[0]['all_children'];
            }
        }
        // 大区的用户id
        $max = $maxArray[0]['user_id'];
        $Share = new Share();
        // 初始化存储所有下级ID及相应信息的数组
        $allDescendants = [];
        function get_all_descendants($pid, &$User, &$Share, &$descendants)
        {
            // 获取当前层级用户的基本信息
            $userInfo = $User->field('id,avatar,nickname')->where(['pid' => $pid])->select()->toArray();
            // 获取当前层级用户的active_zong信息
            $userActiveInfo = $Share->field('user_id,active_zong')->where(['user_id' => $pid])->find();
            $activeZong = $userActiveInfo ? $userActiveInfo['active_zong'] : null;
            foreach ($userInfo as $user) {
                // 添加用户完整信息（包含active_zong）到结果集
                $descendants[] = [
                    'id' => $user['id'],
                    'avatar' => $user['avatar'],
                    'nickname' => $user['nickname'],
                    'active_zong' => $activeZong, // 这里假设大区用户的active_zong对下级用户同样有效，如果不是这样，请在下一级递归中获取active_zong
                ];
                // 递归获取该用户的下级及其active_zong信息
                get_all_descendants($user['id'], $User, $Share, $descendants);
            }
        }
        get_all_descendants($max, $User, $Share, $allDescendants);
        $this->success('', ['大区用户信息及active_zong值：' => $allDescendants]);
    }

    /**
     * 立即签到
     * @ApiMethod (GET)
     **/
    public function dosign()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);


        $config = get_addon_config('signin');
        $signdata = $config['signinscore'];

        $lastdata = \addons\signin\model\Signin::where('user_id', $uid)->order('createtime', 'desc')->find();
        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
        $signin = \addons\signin\model\Signin::where('user_id', $uid)->whereTime('createtime', 'today')->find();
        if ($signin) {
            $this->error('今天已签到,请明天再来!');
        } else {
            $successions++;
            $score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
            Db::startTrans();
            try {
                \addons\signin\model\Signin::create(['user_id' => $uid, 'successions' => $successions, 'createtime' => time()]);
                \app\common\model\User::score($score, $uid, "连续签到{$successions}天");
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('签到失败,请稍后重试');
            }
            $this->success('签到成功!连续签到' . $successions . '天!获得' . $score . '积分');
        }
    }


    /**
     * 签到信息
     * @ApiMethod (GET)
     **/
    public function sign()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $lastdata = \addons\signin\model\Signin::where('user_id', $uid)->order('createtime', 'desc')->find();

        $config = get_addon_config('signin');
        $signdata = $config['signinscore'];
        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
        $successions++;
        $score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
        $lastdata['score'] = $score;

        $this->success('', $lastdata);
    }


    /**
     * cdk兑换列表
     * @ApiMethod (GET)
     **/
    public function cdk()
    {
        $cdklist = Db::table('fa_cdk')->order('weigh asc')->select();
        $this->success('成功', $cdklist);
    }


    /**
     * 设置交易密码
     * @ApiMethod (GET)
     * @param string pay_pass 密码
     * @param string mobile  手机号
     * @param string captcha 验证码
     **/
    public function setpassword()
    {


        $user = $this->auth->getUser();
        $captcha = $this->request->get('captcha');
        $mobile = $this->request->get('mobile');
        $pay_pass = $this->request->get('pay_pass');

        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        $result = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $user->verification = $verification;

        $userInfo = $this->auth->getUser();
        $userInfo->pay_pass = $pay_pass;
        $userInfo->save();
        Sms::flush($mobile, 'resetpwd');
        $this->success('设置成功');
    }

    /**
     * 判断是否设置免密支付
     * @ApiMethod (GET)
     **/
    public function getnopassword()
    {
        $userInfo = $this->auth->getUser();
        if ($userInfo->no_pass == 1) {
            $this->success('未设置', $userInfo->no_pass);
        }
        $this->success('已设置', $userInfo->no_pass);
    }


    /**
     * 判断是否设置交易密码
     * @ApiMethod (GET)
     **/
    public function getpassword()
    {
        $userInfo = $this->auth->getUser();
        if ($userInfo->pay_pass == '') {
            $this->success('未设置', 0);
        }
        $this->success('已设置', 1);
    }

    /**
     * 判断交易密码是否正确接口
     * @ApiMethod (GET)
     * @param string pay_pass 密码
     **/
    public function truepassword()
    {
        $pay_pass = $this->request->get('pay_pass');
        $userInfo = $this->auth->getUser();
        if ($userInfo->pay_pass != $pay_pass) {
            $this->error('密码错误');
        }
        $this->success('密码一致');
    }

    /**
     * 免密支付设置
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     *
     */
    public function setnopass()
    {
        $user = $this->auth->getUser();
        $captcha = $this->request->post('captcha');
        $mobile = $this->request->post('mobile');
        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        $result = Sms::check($mobile, $captcha, 'notice');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $user->verification = $verification;
        if ($user->no_pass == 1) {
            $user->no_pass = 2;
        } else {
            $user->no_pass = 1;
        }
        $user->save();

        Sms::flush($mobile, 'notice');
        $this->success('设置成功');
    }

    /**
     * 获取是否实名认证1是0否
     * @ApiMethod (get)
     */
    public function shiming()
    {
        $user = $this->auth->getUser();
        if ($user->id_card != '' && $user->username != '' && $user->facePhotoUrl != '') {
            $this->success('已实名', 1);
        }
        $this->success('未实名', 0);
    }


    /**
     * 获取实名认证奖励是否领取0=否,1=是
     * @ApiMethod (get)
     */
    public function shiming_score()
    {
        $user = $this->auth->getUser();
        if ($user->shi_score == 1) {
            $this->success('已领取', 1);
        }
        $this->success('未领取', 0);
    }

    /**
     * 实名认证奖励领取接口
     * @ApiMethod (get)
     */
    public function renzheng_score()
    {
        $user = $this->auth->getUser();
        if ($user->id_card == '' && $user->username == '' && $user->facePhotoUrl == '') {
            $this->error('未实名认证');
        }

        if ($user->shi_score == 1) {
            $this->error('请勿重复领取');
        }
        $site = config('site');
        \app\common\model\User::score($site['shiming'], $user->id, "实名认证奖励");

        $user->shi_score = 1;
        $user->save();
        $this->success('领取成功');

    }

    /**
     * 实名认证接口
     * @ApiMethod (POST)
     * @param string $name 姓名
     * @param string $idCardNo 身份证号
     * @param string $facePhotoUrl 人脸照片地址
     */
    public function renzheng()
    {
        $name = $this->request->post('name');
        $idCardNo = $this->request->post('idCardNo');
        $facePhotoUrl = $this->request->post('facePhotoUrl');
        $user = $this->auth->getUser();


        $count = (new \app\admin\model\User())->where(['id_card' => $idCardNo])->count();
        if ($count > 1) {
            $this->error('该身份证已被绑定');
        }

        $host = "https://jmfaceid.market.alicloudapi.com";
        $path = "/idcard-face/validate";
        $method = "POST";
        $appcode = "01dbc16d52064dd4b26710392c530697";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = 'facePhotoUrl=' . $facePhotoUrl . '&idCardNo=' . $idCardNo . '&name=' . $name;
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设定返回信息中是否包含响应信息头，启用时会将响应信息头作为数据流输出，true 表示输出信息头, false表示不输出信息头
        //如果想将响应结果json字符串转为json数组，建议将 CURLOPT_HEADER 设置成 false
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $reponse = curl_exec($curl);
        curl_close($curl);
        $res = (array)json_decode($reponse, true);

        if ($res['code'] != 200) {
            $this->error($res['msg']);
        }

        $incorrect = $res['data']['incorrect'];

        if ($incorrect != 100) {
            $this->error($res['data']['msg']);
        }

        $user->id_card = $idCardNo;
        $user->username = $name;
        $user->facePhotoUrl = $facePhotoUrl;
        $user->save();
        $this->success('设置成功', $res['data']);
    }


}
